package cn.edu.flink.tutorial.sink;

import cn.edu.flink.tutorial.source.Sensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Collections;

public class JdbcSink extends RichSinkFunction<Sensor> {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Sensor> streamSource = env.fromCollection(Collections.singletonList(new Sensor("1", System.currentTimeMillis(), 23)));

        streamSource.addSink(new JdbcSink());

        env.execute();

    }


    Connection conn = null;
    PreparedStatement insertStmt = null;


    @Override
    public void open(Configuration parameters) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");

        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");

        insertStmt = conn.prepareStatement("insert into ecodata values (?, ?)");
    }

    @Override
    public void close() throws Exception {
        insertStmt.close();
        conn.close();
    }

    @Override
    public void invoke(Sensor value, Context context) throws Exception {
        insertStmt.setString(1, value.getName());
        insertStmt.setDouble(2, value.getValue());
        insertStmt.execute();
    }
}
